<?php
use lib\AesRsa_Encrypter;

//过滤

function checkNameInArray($url) {
    $array = [
        // 'mzf.daoh.top',
        'yuntz.huiqiming.cn'
        ];
    return in_array($url, $array, true);
}
function daddslashes($string) {
    $ra = Array('/script/','/javascript/','/vbscript/','/expression/','/applet/','/meta/','/xml/','/blink/','/link/','/style/','/embed/','/object/','/frame/','/layer/','/bgsound/','/base/','/onload/','/onunload/','/onchange/','/onsubmit/','/onreset/','/onselect/','/onblur/','/onfocus/','/onabort/','/onkeydown/','/onkeypress/','/onkeyup/','/onclick/','/ondblclick/','/onmousedown/','/onmousemove/','/onmouseout/','/onmouseover/','/onmouseup/','/onunload/');
    
    if (is_array($string)) {
        foreach ($string as $key => $value) {
            if (!is_array($value)) {
                // 检查 magic_quotes_gpc 配置的状态
                if (!ini_get('magic_quotes_gpc')) {
                    $value = addslashes($value);
                }
                
                // 使用 stripslashes 处理 magic_quotes_gpc 转义过的字符
                $value = stripslashes($value);

                // 删除非打印字符，粗暴式过滤 XSS 可疑字符串
                $value = preg_replace($ra, '', $value);

                // 去除 HTML 和 PHP 标记并转换为 HTML 实体
                $string[$key] = htmlentities(strip_tags($value));
            } else {
                // 递归调用
                $string[$key] = daddslashes($value);
            }
        }
    }

    return $string;
}
function hello_user($name){
    $date = date("H:i:s");
	if($date >= '03:00:00' && $date < '06:00:00'){
		return '凌晨好，'.$name;
	}elseif($date >= '06:00:00' && $date < '08:00:00'){
        return '早晨好，'.$name;
    }elseif($date >= '08:00:00' && $date < '11:00:00'){
        return '上午好，'.$name;
    }elseif($date >= '11:00:00' && $date < '13:00:00'){
        return '中午好，'.$name;
    }elseif($date >= '13:00:00' && $date < '17:00:00'){
        return '下午好，'.$name;
    }elseif($date >= '17:00:00' && $date < '19:00:00'){
        return '傍晚好，'.$name;
    }elseif($date >= '19:00:00' && $date < '23:00:00'){
        return '晚上好，'.$name.'<i class="layui-icon layui-icon-heart-fill" style="color:red"></i>~';
    }else{
        return '深夜了，我去睡觉了，'.$name.'也早点睡觉吧<i class="layui-icon layui-icon-heart-fill" style="color:red"></i>~';
	}
}
//生成随机数字
function randpw($len=8,$format='ALL'){
    $is_abc = $is_numer = 0;
    $password = $tmp ='';
    switch($format){
        case 'ALL':
            $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        break;
        case 'CHAR':
            $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
        break;
        case 'NUMBER':
            $chars='0123456789';
        break;
        default :
            $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        break;
    }
    mt_srand((double)microtime()*1000000*getmypid());
    while(strlen($password)<$len){
        $tmp =substr($chars,(mt_rand()%strlen($chars)),1);
        if(($is_numer <> 1 && is_numeric($tmp) && $tmp > 0 )|| $format == 'CHAR'){
            $is_numer = 1;
        }
        if(($is_abc <> 1 && preg_match('/[a-zA-Z]/',$tmp)) || $format == 'NUMBER'){
            $is_abc = 1;
        }
        $password.= $tmp;
    }
    if($is_numer <> 1 || $is_abc <> 1 || empty($password) ){
        $password = randpw($len,$format);
    }
    return $password;
}
function postJson_curl($url, $data, $headers = []) {
    // 初始化 cURL
    $ch = curl_init($url);

    // 默认头信息
    $defaultHeaders = [
        'Content-Type: application/json',
        'Accept: application/json'
    ];

    // 合并自定义头信息
    foreach ($headers as $key => $value) {
        $defaultHeaders[] = "$key: $value";
    }

    // 配置 cURL 选项
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $defaultHeaders);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

    // 执行请求
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    // 检查错误
    if (curl_errno($ch)) {
        $error = curl_error($ch);
        curl_close($ch);
        return [
            'status' => 'error',
            'http_code' => $httpCode,
            'message' => $error
        ];
    }

    // 关闭 cURL
    curl_close($ch);

    // 返回响应
    return [
        'status' => 'success',
        'http_code' => $httpCode,
        'response' => $response // 解码 JSON 响应
    ];
}
function get_curl($url,$post=false,$referer=0,$cookie=0,$header=0,$ua=0,$nobaody=0){
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL,$url);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
	$httpheader[] = "Accept:*/*";
	$httpheader[] = "Accept-Encoding:gzip,deflate,sdch";
	$httpheader[] = "Accept-Language:zh-CN,zh;q=0.8";
	$httpheader[] = "Connection:close";
	curl_setopt($ch, CURLOPT_HTTPHEADER, $httpheader);
	curl_setopt($ch, CURLOPT_TIMEOUT, 180);
	if($post){
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
	}
	if($header){
		curl_setopt($ch, CURLOPT_HEADER, TRUE);
	}
	if($cookie){
		curl_setopt($ch, CURLOPT_COOKIE, $cookie);
	}
	if($referer){
		if($referer==1){
			curl_setopt($ch, CURLOPT_REFERER, 'http://m.qzone.com/infocenter?g_f=');
		}else{
			curl_setopt($ch, CURLOPT_REFERER, $referer);
		}
	}
	if($ua){
		curl_setopt($ch, CURLOPT_USERAGENT,$ua);
	}else{
		curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Linux; U; Android 4.4.1; zh-cn; R815T Build/JOP40D) AppleWebKit/533.1 (KHTML, like Gecko)Version/4.0 MQQBrowser/4.5 Mobile Safari/533.1');
	}
	if($nobaody){
		curl_setopt($ch, CURLOPT_NOBODY,1);
	}
	curl_setopt($ch, CURLOPT_ENCODING, "gzip");
	curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
	$ret = curl_exec($ch);
	curl_close($ch);
	return $ret;
}
function yiyan(){
   $httpyts='https://auth.daoh.top/api/yiye.php';  
  $tijiao =  @get_curl($httpyts);  
   $wenzi1= '不论顺流还是逆风，都按照自己的节奏，随着自己的心意，用心生活，用力向上。';
   if($tijiao){
      return  $tijiao;
   }else{
       return $wenzi1;
   }
}
function mapijson($code,$msg,$data){
    exit(json_encode(array(
        "code"=>$code,
        "msg"=>$msg,
        "money"=>$data['money'],
        "type"=>$data['type'],
        "qrcode"=>$data['qrcode'],
        "code_url"=>$data['code_url'],
        "trade_no"=>$data['trade_no'],
        "out_trade_no"=>$data['out_trade_no']
        )));
}
//获取网络请求数据
function input($method = null) {
   if ($method == 'post') {
        $data = $_POST;
    } elseif ($method == 'get') {
        $data = $_GET;
    } elseif($method  == 'cookie'){
        $data = $_COOKIE;
    } elseif($method == 'input'){
        $data = json_decode(file_get_contents('php://input'), true);
    }
    else {
        // 如果未指定，则合并 POST 和 GET 变量
        $data = array_merge($_POST, $_GET);
    }
    $filteredData = array_map('strip_tags', $data);
    $filteredData = daddslashes($filteredData);
     return $filteredData;
    
}

function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {
	$ckey_length = 4;
	//$key = md5($key ? $key : ENCRYPT_KEY);
	$keya = md5(substr($key, 0, 16));
	$keyb = md5(substr($key, 16, 16));
	$keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';
	$cryptkey = $keya.md5($keya.$keyc);
	$key_length = strlen($cryptkey);
	$string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
	$string_length = strlen($string);
	$result = '';
	$box = range(0, 255);
	$rndkey = array();
	for($i = 0; $i <= 255; $i++) {
		$rndkey[$i] = ord($cryptkey[$i % $key_length]);
	}
	for($j = $i = 0; $i < 256; $i++) {
		$j = ($j + $box[$i] + $rndkey[$i]) % 256;
		$tmp = $box[$i];
		$box[$i] = $box[$j];
		$box[$j] = $tmp;
	}
	for($a = $j = $i = 0; $i < $string_length; $i++) {
		$a = ($a + 1) % 256;
		$j = ($j + $box[$a]) % 256;
		$tmp = $box[$a];
		$box[$a] = $box[$j];
		$box[$j] = $tmp;
		$result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
	}
	if($operation == 'DECODE') {
		if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
			return substr($result, 26);
		} else {
			return '';
		}
	} else {
		return $keyc.str_replace('=', '', base64_encode($result));
	}
}
//返回json 
function exitjson($code, $msg, $data = null) {
    if ($data !== null) {
        exit(json_encode(array("code" => $code, "msg" => $msg, "data" => $data)));
    } else {
        exit(json_encode(array("code" => $code, "msg" => $msg)));
    }
}
//执行sql操作
function executeSQLQuery($sql, $operation = 'select') {
    global $DB;
    try {
        $stmt = $DB->prepare($sql);
        $stmt->execute();
        if ($operation === 'select') {
            return $stmt->fetch(PDO::FETCH_ASSOC);
        } elseif ($operation === 'delete' || $operation === 'update' || $operation === 'insert') {
            return $stmt->rowCount(); // 返回受影响的行数
        } else {
            return false;
        }
    } catch (PDOException $e) {
        return false;
    }
}
//执行sql操作 并防范sql注入函数  查询支持返回 数量 和记录集
function safeSqlQuery($sql, $params, $operation = 'select') {
    global $DB;

    // 使用 PDO 预处理语句执行查询
    $stmt = $DB->prepare($sql);

    // 绑定参数
    foreach ($params as $paramName => &$paramValue) {
        $stmt->bindParam(":$paramName", $paramValue, PDO::PARAM_STR);
    }
    // 执行查询
    $stmt->execute();

    // 根据操作类型返回结果
    switch (strtolower($operation)) {
        case 'select':
            // 获取实际的结果集
            $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
            // 获取记录数量
            $count = count($result);
            return ['result' => $result, 'count' => $count];
            break;
        case 'insert':
            if(!$DB->lastInsertId()) return $stmt->rowCount();
             return $DB->lastInsertId();
            break;
        case 'update':
        case 'delete':
            // 返回受影响的行数
            return $stmt->rowCount();
            break;

        default:
            // 如果提供的操作不在支持范围内，返回空数组
            return false;
    }
}
function createLog($uid='0', $type, $ip) {
    global $DB; 
    if($uid == 'admin')$uid = 0;
    // 准备 SQL 语句
    $sql = "INSERT INTO `pay_log` (`pid`, `type`, `ip`, `date`) VALUES (:pid, :type, :ip, NOW())";
    try {
        // 准备并执行 SQL 查询
        $stmt = $DB->prepare($sql);
        $stmt->bindParam(':pid', $uid, PDO::PARAM_STR);
        $stmt->bindParam(':type', $type, PDO::PARAM_STR);
        $stmt->bindParam(':ip', $ip, PDO::PARAM_STR);
        $stmt->execute();

        // 返回成功
        return true;
    } catch (PDOException $e) {
        // 返回失败并输出异常信息
        return false;
    }
}
function DeleteHtml($str) 
{ 
    $str = trim($str); //清除字符串两边的空格
    $str = preg_replace("/\t/","",$str); //使用正则表达式替换内容，如：空格，换行，并将替换为空。
    $str = preg_replace("/\r\n/","",$str); 
    $str = preg_replace("/\r/","",$str); 
    $str = preg_replace("/\n/","",$str); 
    $str = preg_replace("/ /","",$str);
    $str = preg_replace("/  /","",$str);  //匹配html中的空格
    return trim($str); //返回字符串
}
function getSubstr($str, $leftStr, $rightStr)
{
    $left = strpos($str, $leftStr);
    //echo '左边:'.$left;
    $right = strpos($str, $rightStr,$left);
    //echo '<br>右边:'.$right;
    if($left < 0 or $right < $left) return '';
    return substr($str, $left + strlen($leftStr), $right-$left-strlen($leftStr));
}
function http_ip(){
    if(getenv('HTTP_CLIENT_IP')){
        $ip = getenv('HTTP_CLIENT_IP');
     }
    elseif(getenv('HTTP_X_FORWARDED_FOR')){
      $ip = getenv('HTTP_X_FORWARDED_FOR');
    }
    elseif(getenv('REMOTE_ADDR')){
      $ip = getenv('REMOTE_ADDR');
    }
    else{
      $ip = $HTTP_SERVER_VARS['REMOTE_ADDR'];
    }
    return $ip;
}
//邮箱发信
function send_mail($to, $sub, $msg) {
	global $conf;
	if($conf['mail_cloud']==1){
		$mail = new \lib\mail\Sendcloud($conf['mail_apiuser'], $conf['mail_apikey']);
		return $mail->send($to, $sub, $msg, $conf['mail_name2'], $conf['sitename']);
	}elseif($conf['mail_cloud']==2){
		$mail = new \lib\mail\Aliyun($conf['mail_apiuser'], $conf['mail_apikey']);
		return $mail->send($to, $sub, $msg, $conf['mail_name2'], $conf['sitename']);
	}else{
		if(!$conf['mail_name'] || !$conf['mail_port'] || !$conf['mail_smtp'] || !$conf['mail_pwd'])return false;
		$port = intval($conf['mail_port']);
		$mail = new \lib\mail\PHPMailer\PHPMailer(true);
		try{
			$mail->SMTPDebug = 0;
			$mail->CharSet = 'UTF-8';
			$mail->Timeout = 5;
			$mail->isSMTP();
			$mail->Host = $conf['mail_smtp'];
			$mail->SMTPAuth = true;
			$mail->Username = $conf['mail_name'];
			$mail->Password = $conf['mail_pwd'];
			if($port == 587) $mail->SMTPSecure = 'tls';
			else if($port >= 465) $mail->SMTPSecure = 'ssl';
			else $mail->SMTPAutoTLS = false;
			$mail->Port = intval($conf['mail_port']);
			$mail->setFrom($conf['mail_name'], $conf['sitename']);
			$mail->addAddress($to);
			$mail->addReplyTo($conf['mail_name'], $conf['sitename']);
			$mail->isHTML(true);
			$mail->Subject = $sub;
			$mail->Body = $msg;
			$mail->send();
			return true;
		} catch (Exception $e) {
			return $mail->ErrorInfo;
		}
	}
}

//短信发信
function send_sms($phone,$code,$scope='reg'){
    global $conf;
    switch ($conf['sms_api']){
        case '1':
            if($scope=='reg'){
                 $templId=$conf['sms_tpl_reg']?$conf['sms_tpl_reg']:$conf['sms_tpl_univer'];
            }else if($scope == 'find'){
                 $templId=$conf['sms_tpl_find']?$conf['sms_tpl_find']:$conf['sms_tpl_univer'];
            }else if($scope == 'edit'){
                $templId=$conf['sms_tpl_modify']?$conf['sms_tpl_modify']:$conf['sms_tpl_univer'];
            }else if($scope == 'regsucc'){
                $json=json_decode($code,true);
                $templId=$conf['sms_tpl_phonesuccid'];
            }else if($scope == 'auth'){
                $templId=$conf['sms_tpl_phoneauth']?$conf['sms_tpl_phoneauth']:$conf['sms_tpl_univer'];
            }
            if (!empty($conf['sms_appid']) && !empty($conf['sms_appkey']) && !empty($conf['sms_sign']) && !empty($templId)) {
                 $tencentSms = new \lib\sms\TencentSms($conf['sms_appid'], $conf['sms_appkey']);
                 if($scope == 'regsucc'){
                      $params=array($json['user'],$json['pwd']);
                      
                 }else{
                      $params=array($code,'5'); 
                 }
                 $result = $tencentSms->sendWithParam("86", $phone, $templId, $params, $conf['sms_sign']);
                 if(!empty($result)){
                     $json=json_decode($result,true);
                     if($json['result']==0){
                         $arr=array("code"=>200,"msg"=>"腾讯云测试发信成功");
                     }else{
                         $arr=array("code"=>-1,"msg"=>"短信发送失败:".$json['errmsg']);
                     }
                 }else{
                     $arr=array("code"=>-1,"msg"=> "发送请求失败，请检查网络或接口配置");
                 }
            }else{
                $arr=array("code"=>-1,"msg"=> "缺少必要的参数，请确保配置了 appid、appkey、签名 和 短信模板");
            }
            return json_encode($arr);
          break;
         case '2': 
             if($scope=='reg'){
                  $template=$conf['ali_sms_regid']?$conf['ali_sms_regid']:$conf['ali_sms_univer'];
                }elseif($scope=='find'){
                   $template=$conf['ali_sms_find']?$conf['ali_sms_find']:$conf['ali_sms_univer'];
                }else if($scope=='edit'){
                   $template=$conf['ali_sms_modify']?$conf['ali_sms_modify']:$conf['ali_sms_univer'];  
                }
             if(!empty($conf['ali_sms_akid']) && !empty($conf['ali_sms_aks']) && !empty($conf['ali_sms_qm']) && !empty($template)){
                   $aliyunSMS = new \lib\sms\Aliyun($conf['ali_sms_akid'], $conf['ali_sms_aks']);
                  $result = $aliyunSMS->send($phone, $code, $template, $conf['ali_sms_qm']);
                  if(isset($result['Code']) && $result['Code'] == "OK"){
                      $arr=array("code"=>200,"msg"=>"阿里云测试发信成功");
                  }else{
                    $arr=array("code"=>-1,"msg"=>isset($result['Message']) ? $result['Message'] : '未知错误');  
                  }
             }else{
                   $arr=array("code"=>-1,"msg"=> "缺少必要的参数，请确保配置了 appid、appkey、签名 和 短信模板");
             }
            return json_encode($arr);
         break;
         case '3':
             if($scope=='reg'){//注册
                $content = "【".$conf['smsbao_qm']."】您正在进行手机注册,您的验证码为：".$code."，该验证码在5分钟内有效，如非本人操作请忽略";
            }else if($scope=='find'){//找回
                $content ="【".$conf['smsbao_qm']."】您正在申请找回密码，您的验证码为：".$code."，该验证码在5分钟内有效，如非本人操作请忽略，并及时修改密码避免被盗";
            }else if($scope=='regsucc'){//注册成功通知
                $json=json_decode($code,true);
                 $content ="【".$conf['smsbao_qm']."】恭喜您注册成功！您的注册平台账号为：".$json['user']."，您的平台密码为：".$json['pwd']."，请牢记您的账号和密码并妥善保管，避免被盗！";
            }else if($scope == 'edit'){//修改密码
                $content ="【".$conf['smsbao_qm']."】您正在操作修改密码，您的验证码为：".$code."，该验证码在5分钟内有效，如非本人操作请忽略，并及时修改密码避免被盗";
            }
             if(!empty($conf['smsbao_user']) && !empty($conf['smsbao_key']) && !empty($conf['smsbao_qm'])){
                 $smsbao=json_decode(sms_bao($conf['smsbao_user'],$conf['smsbao_key'],$phone,$content),true);
                 if($smsbao['code']==0){
                      $arr=array("code"=>200,"msg"=>"短信宝测试发信成功");
                 }else{
                     $arr=array("code"=>$smsbao['code'],"msg"=>isset($smsbao['msg']) ? $smsbao['msg'] : '未知错误');  
                 }
             }else{
                   $arr=array("code"=>-1,"msg"=>"缺少必要的参数，请确保配置了 短信宝账号、短信宝key、签名 ");  
             }
             return json_encode($arr);
         break;   
          
    }
}
//短信宝 对接
function sms_bao($user,$pass,$phone,$content){
    $statusStr = array(
        "0" => "短信发送成功",
        "-1" => "参数不全",
        "-2" => "服务器空间不支持,请确认支持curl或者fsocket，联系您的空间商解决或者更换空间！",
        "30" => "密码错误",
        "40" => "账号不存在",
        "41" => "余额不足",
        "42" => "帐户已过期",
        "43" => "IP地址限制",
        "50" => "内容含有敏感词"
    );
   $smsapi = "http://api.smsbao.com/";
   $sendurl = $smsapi."sms?u=".$user."&p=".$pass."&m=".$phone."&c=".urlencode($content);
   $result=get_curl($sendurl);
   return json_encode(array("code"=>$result,"msg"=>$statusStr[$result]));
}
function aes256auth($data,$key,$operation='ENCODE'){//aes 256 加密
    if($operation == 'DECODE'){//解密
        $data = base64_decode($data);
         $decodedData = base64_decode($data);//两次 b64解密
          $iv = substr($decodedData, 0, 16);//取解密后的前16位作为 iv
          $encryptedData = substr($decodedData, 16);//取16位后面的作为解密内容
          $openssl=openssl_decrypt($encryptedData, 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv);//进行解密
          if($openssl === false){
              return false;
          }
          return base64_decode($openssl);//解密成功 在进行一次 b64解密并返回解密后的字符
    }else{//加密
        $data = base64_encode($data);//对原始数据 b64 加密一次
        $iv = random_bytes(16);//随机生成 16位作为 iv加密字符
        $encryptedData = openssl_encrypt($data, 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv);//进行加密
        $encodedData = base64_encode($iv . $encryptedData);//拼接数据  并 b64加密一次
        return base64_encode($encodedData);//在加密一次
    }
}

function download_zip($zip_name,$zip_url)
{
    ob_start(); //打开输出
    readfile($zip_url); //输出图片文件
    $zip = ob_get_contents(); //得到浏览器输出
  
    ob_end_clean(); //清除输出并关闭
    file_put_contents($zip_name, $zip);
	mkdir('../'.dirname(__FILE__).$zip_name, 0777);
	@chmod('../'.dirname(__FILE__).$zip_name, 0777);
    return $zip_name;
}
function zipExtract($src, $dest)
{
  $zip = new ZipArchive();
  if ($zip->open($src) === true) {
    $zip->extractTo($dest);
    $zip->close();
    return true;
  }
  return false;
}
function get_zip_originalsize($filename, $path) {
  //先判断待解压的文件是否存在
  if(!file_exists($filename)){
   exit(json_encode(array("code"=>-1,"msg"=>"文件".$filename."不存在")));
  }
  $starttime = explode(' ',microtime()); //解压开始的时间

  //将文件名和路径转成windows系统默认的gb2312编码，否则将会读取不到
  $filename = iconv("utf-8","gb2312",$filename);
  $path = iconv("utf-8","gb2312",$path);
  //打开压缩包
  $resource = zip_open($filename);
  $i = 1;
  //遍历读取压缩包里面的一个个文件
  while ($dir_resource = zip_read($resource)) {
    //如果能打开则继续
    if (zip_entry_open($resource,$dir_resource)) {
      //获取当前项目的名称,即压缩包里面当前对应的文件名
      $file_name = $path.zip_entry_name($dir_resource);
      //以最后一个“/”分割,再用字符串截取出路径部分
      $file_path = substr($file_name,0,strrpos($file_name, "/"));
      //如果路径不存在，则创建一个目录，true表示可以创建多级目录
      if(!is_dir($file_path)){
        mkdir($file_path,0777,true);
      }
      //如果不是目录，则写入文件
      if(!is_dir($file_name)){
        //读取这个文件
        $file_size = zip_entry_filesize($dir_resource);
        //最大读取6M，如果文件过大，跳过解压，继续下一个
        if($file_size<(1024*1024*30)){
          $file_content = zip_entry_read($dir_resource,$file_size);
          file_put_contents($file_name,$file_content);
        }else{
          return $i++." 此文件已被跳过，原因：文件过大， -> ".iconv("gb2312","utf-8",$file_name);
        }
      }
      //关闭当前
      zip_entry_close($dir_resource);
    }
  }
  //关闭压缩包
  zip_close($resource);
  $endtime = explode(' ',microtime()); //解压结束的时间
  $thistime = $endtime[0]+$endtime[1]-($starttime[0]+$starttime[1]);
  $thistime = round($thistime,3); //保留3为小数
  return "解压完毕！，本次解压花费：$thistime 秒。";
}

function getdomain($url){//获取域名
	$arr=parse_url($url);
	return $arr['host'];
}
function isMobile(){    
    $useragent=isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';    
    $useragent_commentsblock=preg_match('|\(.*?\)|',$useragent,$matches)>0?$matches[0]:'';      
    function CheckSubstrs($substrs,$text){    
        foreach($substrs as $substr)    
            if(false!==strpos($text,$substr)){    
                return true;    
            }    
            return false;    
    }  
    $mobile_os_list=array('Google Wireless Transcoder','Windows CE','WindowsCE','Symbian','Android','armv6l','armv5','Mobile','CentOS','mowser','AvantGo','Opera Mobi','J2ME/MIDP','Smartphone','Go.Web','Palm','iPAQ');  
    $mobile_token_list=array('Profile/MIDP','Configuration/CLDC-','160×160','176×220','240×240','240×320','320×240','UP.Browser','UP.Link','SymbianOS','PalmOS','PocketPC','SonyEricsson','Nokia','BlackBerry','Vodafone','BenQ','Novarra-Vision','Iris','NetFront','HTC_','Xda_','SAMSUNG-SGH','Wapaka','DoCoMo','iPhone','iPod');    
                
    $found_mobile=CheckSubstrs($mobile_os_list,$useragent_commentsblock) ||    
              CheckSubstrs($mobile_token_list,$useragent);    
                
    if ($found_mobile){    
        return true;    
    }else{    
        return false;    
    }    
} 
 //字符组合
function random($length){
 $str = 'zerointlabcdfghjkmpqsuvwxyxZEROABCDFGHIJKLMNPQSTUVWXY0123456789';
 $len = strlen($str)-1;
 $randstr = '';
 for($i=0;$i<$length;$i++) {
	$num=mt_rand(0,$len);
	$randstr .= $str[$num];
 }
 return $randstr;
}

//注册成功通知
function send_regsucc($user,$pwd,$to=null,$send=false){
    global $conf,$httphost;
    $send_sms=false;
    if(!$send){
        if($conf['verifytype'] == 'phone' && !empty($to)){
            if($conf['sms_api'] == 1 && !empty($conf['sms_tpl_phonesuccid'])){//判断 如果是腾讯云短信则检测 发信是否为空如果不为空则正常发信
                    $send_sms=true;
                }
            if($conf['sms_api'] == 3){//短信宝直接通过
                $send_sms=true;
            }
        }
       
        if($send_sms){
            $arr=json_encode(array('user'=>$user,'pwd'=>$pwd));
            send_sms($to,$arr,'regsucc');
        }
    }else{
        $sub=$conf['sitename'].'- 注册成功提醒';
        $data=[
            'user' => $user,
            'paragraphs' => [
                    ['label' => '恭喜您注册成功!', 'value' => ''],
                    ['label' => '您的注册平台账号为:', 'value' => $user],
                    ['label' => '您的平台密码为:', 'value' => $pwd],
                    ['label' => '请牢记您的账号和密码并妥善保管，避免被盗！', 'value' => ''],
                    ['label' => '站点地址:', 'value' => $httphost,'fontSize'=>'12'],
                    ['label' => '有问题请联系站长QQ:', 'value' => $conf['qq'],'fontSize'=>'12'],
                ]
            ];
            $msg = Mailbox_sending_template($data, '注册成功通知');
            send_mail($to, $sub, $msg);
    }
}

function xfhttp_post_yun($url, $Header, $data=NULL){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $Header);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POST, 1); // 发送一个常规的Post请求
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); // Post提交的数据包
    curl_setopt($ch, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
    curl_setopt($ch, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
    $sResult = curl_exec($ch);
    if($sError=curl_error($ch)){
        die($sError);
    }
    curl_close($ch);
    return $sResult;
}

function base64_image_content($base64_image_content,$path,$trade_no){
    //匹配出图片的格式
    if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){
        $type = $result[2];
        // $new_file = $path."/".date('Ymd',time())."/";
        $new_file = $path."/";
        if(!file_exists($new_file)){
            //检查是否有该文件夹，如果没有就创建，并给予最高权限
            mkdir($new_file, 0700);
        }
        $new_file = $path.$trade_no.".png";
        if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_image_content)))){
            return '/'.$new_file;
        }else{
            return false;
        }
    }else{
        return false;
    }
}
function deleteimg($trade_no=NULL){
    if($trade_no){
        $directory = ROOT.'/Submit/img/wximg/'; 
	 $file = $trade_no.'.png';
	  $filePath = $directory . $file;
	    unlink($filePath);
	    return true;
    }else{
        return false;
    }
}

function insertIntoInsideOrder($order, $pid, $money, $beizhu = '') {
    // 定义 SQL 插入语句
    $sql = "INSERT INTO pay_insideorder (`order`, pid, money, beizhu) VALUES (:order, :pid, :money, :beizhu)";

    // 准备参数
    $params = [
        'order' => $order,
        'pid' => $pid,
        'money' => $money,
        'beizhu' => $beizhu
    ];

    // 执行 SQL 查询
    $result = safeSqlQuery($sql, $params, 'insert');

    // 返回结果
    return $result;
}


function uservips($row){
    $current_time = time(); // 获取当前时间戳

    $expired_count = 0; // 记录过期支付方式的数量

    if ($row['alipay_free_vip_time'] < $current_time) {
        $expired_count++;
    }
    if ($row['wxpay_free_vip_time'] < $current_time) {
        $expired_count++;
    }

    if ($row['qqpay_free_vip_time'] < $current_time) {
        $expired_count++;
    }
    $sql = "update `pay_user` set `user_vips`='0' where `pid`='{$row['pid']}'";
    
    executeSQLQuery($sql,'update');
    uservipsemail($expired_count,$row);
    return "PID:".$row['pid']."通知成功 并关闭状态";
}
function uservipsemail($num,$row){
    global $conf,$httphost;
    $data=[
        'user'=>$row['user'],
        'paragraphs'=>[
            ['label' => '尊敬的用户 PID:', 'value' => $row['pid'].'您好！'],
            ['label' => '您有'.$num.'个支付方式会员已过期,请及时续费否则会影响您的正常使用'],
            ['label'=>'站点地址:','value'=>$httphost,'fontSize'=>12],
            ['label'=>'有问题请联系站长QQ:','value'=>$conf['qq'],'fontSize'=>12]
            ],
        ];
    $email= send_mail($row['email'], $conf['sitename'].'- 会员过期提醒', Mailbox_sending_template($data,'会员过期提醒'));
    return $email;
}

function notify($E_type,$type = null, $money = null , $qr_id = NULL){
    $where = [];
    $params = [];
    if(!empty($type)){
        $where[] = "`type` = :type ";
        $params['type'] = $type;
    }
    if(!empty($money)){
        $where[] = "`price` = :money ";
        $params['money'] = $money;
    }
    if(!empty($qr_id)){
        $where[] = "`qr_id` = :qr_id ";
        $params['qr_id'] = $qr_id;
    }
    $where[] = "`status` = :status AND `outtime` > :outtime ";  
    $params['status'] = 0;
    $params['outtime'] = time();
    $whereClause = !empty($where) ? "WHERE " . implode(" AND ", $where) : "";
    $sql = "SELECT * FROM pay_order  $whereClause limit 1";
    $srow = safeSqlQuery($sql, $params, 'select')['result'][0];
    if($srow){
        if($srow['status'] == 0){
            $xf_pid=$srow['pid'];
           	$xf_money=$srow['price'];
           	$url  =creat_callback($srow);
           	$data = do_notify($url['notify']);
           	xfhtemail($xf_pid,$xf_money,$E_type,$srow['name'],$srow['trade_no']); 
           	createLog($xf_pid,'自动回调订单('.$E_type.')：'.$srow['trade_no'],http_ip());
           	return $data;
        }
    }
    return false;
}
function do_notify($url){
	$return = get_curl($url);
	if(strpos($return,'success')!==false || strpos($return,'SUCCESS')!==false || strpos($return,'Success')!==false){
		return true;
	}else{
		return false;
	}
}




//mac效验码生成
function Machine_effectproduce(){
    global $dbconfig;
    $macAddr = new lib\PHP_Mac('linux');
    $macAddr->parseMacAddr();
    // 获取解析后的MAC地址
    $firstMacAddr = $macAddr->getMacAddr();
    // if(empty($firstMacAddr))return false;
    $host = $_SERVER['HTTP_HOST'];
   
    $cleaned_string = str_replace(":", "", $firstMacAddr);
    
    $hosts = str_replace(".", "", $host);
    $md5 = md5($cleaned_string.$hosts.$dbconfig['xfmzfsqm']);
    $md5_hash_uppercase = strtoupper($md5);
    return $md5_hash_uppercase;
}

function parseUpdateLog($log) {
    $versions = [];
    $lines = explode("\n", $log);
    $current_version = null;
    $current_section = null;

    foreach($lines as $line) {
        $line = trim($line);
        if(empty($line)) continue;

        // 匹配版本和日期
        if(preg_match('/版本号：\s*([\d\.]+)/', $line, $matches)) {
            $current_version = [
                'version' => $matches[1],
                'date' => '',
                'sections' => []
            ];
            $versions[] = &$current_version;
        }
        elseif(preg_match('/发布日期\s*([\d\-年月日]+)/', $line, $matches)) {
            if($current_version) {
                $current_version['date'] = $matches[1];
            }
        }
        // 匹配分类（优化/新增/修复）
        elseif(preg_match('/【(.+?)】/', $line, $matches)) {
            $section_type = $matches[1];
            if($section_type != '伪静态') {  // 排除伪静态部分
                $current_section = [
                    'type' => $section_type,
                    'items' => []
                ];
                if($current_version) {
                    $current_version['sections'][] = &$current_section;
                }
            }
        }
        // 匹配具体项目
        elseif($current_section && preg_match('/^\d+\.(.+)/', $line, $matches)) {
            $current_section['items'][] = trim($matches[1]);
        }
    }
    return $versions;
}




?>